// miniprogram/pages/article/article.js
const db = wx.cloud.database();
const datetime = require('../../utils/datetime');

let url;

Page({
  data: {
    url: {
      type: String,
      value: ''
    },
    busy: {
      type: Boolean,
      value: true
    },
    content: {
      type: Object,
      value: {}
    },
    lastRevisionTime: {
      type: Number,
      value: 0
    },
    time: {
      type: String,
      value: ''
    }
  },

  onLoad: function (options) {
    url = options['url'];
  },

  onReady: function () {
    if (url != null) {
      this.setData({
        url: url,
        busy: true
      });
      this.loadPageData();
    }
  },

  onShareAppMessage: function () {

  },

  loadPageData: function () {
    if (this.data.url.indexOf("http") !== -1) {
      // url
      wx.request({
        url: this.data.url,
        timeout: 10000,
        success: (res) => {
          const str = res.data;
          try {
            const glob = JSON.parse(str);
            this.setData({
              busy: false,
              content: glob.content,
              lastRevisionTime: glob.lastRevisionTime,
              time: datetime.toFriendlyTime(glob.lastRevisionTime)
            });
          } catch (ex) {
            this.setData({
              busy: false,
              content: null
            });  
          }
        },
        fail: () => {
          this.setData({
            busy: false,
            content: null
          });
        },
      });
    } else {
      // db article
      const _ = db.command;
      db.collection('articles').where({
        _id: _.eq(this.data.url)
      }).get()
      .then(data => {
        const article = data.data;
        if (article.length > 0) {
          // render article
          console.log(article[0].content);
          this.setData({
            content: article[0].content,
            lastRevisionTime: article[0].lastRevisionTime,
            time: datetime.toFriendlyTime(article[0].lastRevisionTime)
          });
        }
        this.setData({
          busy: false
        });
      }).catch(e => {
        console.log(e);
      });
    }
  }
})